<template>
  <div>
    <t-steps :current="currentStep">
      <t-step-item title="选择Ruoyi版本" />
      <t-step-item title="选择集成的功能" />
      <t-step-item title="选择导出的选项" />
      <t-step-item title="导出" />
    </t-steps>
    <br />
    <div v-if="currentStep === 0">
      <t-table
        row-key="tag"
        :data="versionData"
        :columns="versionColumn"
        :selected-row-keys="selectedVersionKeys"
        select-on-row-click
        @select-change="rehandleSelectVersion"
      >
        <template #download="scope">
          <t-space>
            <a
              target="_blank"
              :href="
                'https://gitee.com/y_project/RuoYi-Vue/releases/tag/' +
                scope.row.tag
              "
            >
              说明 &nbsp;&nbsp;
            </a>
            <a target="_blank" :href="scope.row.download"> 下载</a>
          </t-space>
        </template>
      </t-table>
    </div>
    <div
      :class="{
        'hiss-show': currentStep === 1,
        'hiss-hide': currentStep != 1
      }"
    >
      <t-enhanced-table
        ref="functionRef"
        row-key="id"
        :data="functionData"
        :columns="functionColumn"
        :defaultExpandedRowKeys="defaultExpandedRowKeys"
        :expand-icon="expandFunctionIcon"
        :selected-row-keys="selectedFunctionKeys"
        select-on-row-click
        :tree="{
          treeNodeColumnIndex: 0,
          indent: 48
        }"
        @select-change="rehandleSelectFunction"
      >
      </t-enhanced-table>
    </div>
    <div v-if="currentStep === 2">
      <t-card :bordered="false" hover-shadow shadow class="config">
        <p>导出量配置：</p>
        <t-radio-group v-model="exp.type">
          <t-radio value="1">增量导出：只导出变更的文件</t-radio>
          <t-radio value="2"
          >全量导出：导出gitee上的文件及合并变更后的文件
          </t-radio
          >
        </t-radio-group>
        <p>导出菜单配置：</p>
        <t-radio-group v-model="exp.sql">
          <t-radio value="1">静态菜单：直接生成路由菜单数据</t-radio>
          <t-radio value="2">动态菜单：生成菜单的SQL文件</t-radio>
        </t-radio-group>
        <p>功能挂载配置：(OA、表单等模块挂载到那个应用)</p>
        <t-radio-group v-model="exp.appId">
          <t-radio v-for="item in appList" :value="item.id">{{
            item.name
          }}</t-radio>
        </t-radio-group>
        <p>流程中心配置：</p>
        <t-form-item label="服务器地址：" label-width="120" style="float: left">
          <t-input v-model="exp.host" style="width: 160px; float: left" />
        </t-form-item>
        <t-form-item label="HTTP端口：" label-width="160" style="float: left; margin-left: 20px">
          <t-input v-model="exp.httpPort" />
        </t-form-item>
        <t-form-item label="TCP端口：" label-width="160" style="float: left; margin-left: 20px">
          <t-input v-model="exp.tcpPort" />
        </t-form-item>
      </t-card>
    </div>
    <div v-if="currentStep === 3">
      <t-card :bordered="false" hover-shadow shadow>
        <t-space direction="vertical">
          <p>
            若依Version：
            <t-tag theme="success" variant="light">{{
              selectedVersionKeys[0]
            }}</t-tag>
          </p>
          <p>
            导出量配置：
            <t-tag theme="warning" variant="light"
              ><span v-if="exp.type === '1'">增量导出</span>
              <span v-else>全量导出</span></t-tag
            >
          </p>
          <p>
            导出菜单配置：
            <t-tag theme="danger" variant="light"
              ><span v-if="exp.sql === '1'">静态菜单</span>
              <span v-else>动态菜单</span></t-tag
            >
          </p>
          <p>
            导出内容：
            <t-row style="padding-top: 10px">
              <t-col
                v-for="item in selectedFunctionRow"
                :span="2"
                style="margin-bottom: 10px"
              >
                <t-tag theme="primary" variant="light" style="color:#666666;">{{ item.name }}</t-tag>
              </t-col>
            </t-row>
          </p>
        </t-space>
      </t-card>
    </div>
    <div class="hiss-step-button">
      <t-space size="24px">
        <t-button
          v-if="currentStep > 0 && !loadSt"
          theme="default"
          @click="handPrve"
        >
          <template #icon>
            <ArrowLeftIcon />
            上一步
          </template>
        </t-button>

        <t-button theme="primary" v-if="currentStep < 3" @click="handNext">
          <template #icon>
            下一步
            <ArrowRightIcon />
          </template>
        </t-button>

        <t-button theme="primary" v-if="currentStep === 3" @click="handExport">
          <template #icon>
            <t-loading v-if="loadSt" indicator class="bt load"></t-loading>
            <DownloadIcon v-else />
            <span v-if="loadSt">导出中，大约需要1分钟......</span>
            <span v-else>开始导出</span>
          </template>
        </t-button>
      </t-space>
    </div>
  </div>
</template>

<script>
import {
  ArrowRightIcon,
  ArrowLeftIcon,
  DownloadIcon
} from 'tdesign-icons-vue-next'
import { RUOYI_CONFIG } from './ruoyi.js'
import { getFormList } from '@/api/form'
import { getApplicationList } from '@/api/application'
import { scaffoldExport } from '@/api/scaffold'
import { MessagePlugin } from "tdesign-vue-next";

export default {
  name: 'Ruoyi',
  components: { ArrowRightIcon, ArrowLeftIcon, DownloadIcon },
  data() {
    return {
      loadSt: false,
      exp: {
        type: '1',
        sql: '1',
        host: 'localhost',
        appId: '',
        httpPort: '8081',
        tcpPort: '10003'
      },
      defaultExpandedRowKeys: [], // 默认展开的功能
      selectedFunctionKeys: [],
      selectedFunctionRow: [],
      selectedVersionKeys: ['v3.8.6'],
      expandFunctionIcon: false,
      appList: [],
      functionData: [],
      functionColumn: RUOYI_CONFIG.funColumns,
      versionData: RUOYI_CONFIG.tags,
      versionColumn: RUOYI_CONFIG.tagColumns,
      currentStep: 0
    }
  },
  mounted() {
    this.fetchApp()
  },
  methods: {
    // 导出
    async handExport() {
      if (this.loadSt) {
        return
      }
      const params = {
        id: 'SCAFFOLD_EXPORT',
        palyload: {
          name: 'RuoYi-Vue',
          ...this.exp,
          templateName: 'ruoyi',
          version: this.selectedVersionKeys[0],
          contents: this.selectedFunctionRow
        }
      }
      try {
        this.loadSt = true
        const res = await scaffoldExport(params)
        const { data, headers } = res
        console.log(res)
        let fileName
        if (headers['content-disposition']) {
          fileName = headers['content-disposition'].replace(
            'attachment; filename="',
            ''
          ).replace('"','')
        } else {
          fileName = data.fileName
        }
        const blob = new Blob([data], { type: headers['content-type'] })
        const dom = document.createElement('a')
        const downUrl = window.URL.createObjectURL(blob)
        dom.href = downUrl
        dom.download = decodeURIComponent(fileName)
        dom.style.display = 'none'
        document.body.appendChild(dom)
        dom.click()
        dom.parentNode.removeChild(dom)
        window.URL.revokeObjectURL('')
        MessagePlugin.success('导出成功!')
      } finally {
        this.loadSt = false
      }
    },
    rehandleSelectVersion(value) {
      this.selectedVersionKeys = value
    },
    rehandleSelectFunction(value, data) {
      this.selectedFunctionKeys = value
      const temp = data.selectedRowData
      this.selectedFunctionRow = []
      for (let i = 0; i < temp.length; i++) {
        let t = temp[i]
        if (t.row) {
          this.selectedFunctionRow.push(t.row)
        } else {
          this.selectedFunctionRow.push(t)
        }
      }
    },
    handPrve() {
      if (this.currentStep > 0) {
        this.currentStep--
      }
    },
    handNext() {
      if (this.currentStep === 0 && this.selectedVersionKeys.length > 0) {
        this.currentStep++
      } else if (this.currentStep === 1) {
        this.currentStep++
      } else if (this.currentStep === 2) {
        this.currentStep++
      }
    },
    fetchApp() {
      const params = {
        id: 'USER_APP_LIST',
        palyload: {}
      }
      getApplicationList(params).then((res) => {
        const temp = JSON.parse(JSON.stringify(RUOYI_CONFIG.funs))
        const arrs = res.data.result.data
        for (let i = 0; i < arrs.length; i++) {
          const obj = arrs[i]
          obj.name = obj.appName
          obj.id = obj.appId
          this.exp.appId = obj.id
          obj.desc = '-------------- 选择项目的表单 ---------------'
          obj.type = 'app'
          this.defaultExpandedRowKeys.push(obj.id)
          this.fetchFormData(obj)
          temp.push(obj)
        }
        this.appList = arrs
        this.functionData = temp
        let _this = this
        setTimeout(() => {
          const functionRef = _this.$refs.functionRef
          functionRef.resetData((_this.functionData = temp))
          functionRef.expandAll()
          console.log(5, _this.functionData)
        }, 1000)
      })
    },
    async fetchFormData(obt) {
      const params = {
        id: 'FORM_MODEL_LIST',
        palyload: {
          userAppId: obt.id
        }
      }
      const res = await getFormList(params)
      if (res.success) {
        const array = res.data.result.data
        for (let i = 0; i < array.length; i++) {
          const form = array[i]
          form.type = 'form'
          form.groupId = obt.id
          form.groupName = obt.name
        }
        obt.children = array
      }
    }
  }
}
</script>

<style scoped>
.hiss-step-button {
  width: 100%;
  text-align: center;
  margin: 30px auto;
  color: #ffffff;
}

.hiss-show {
  display: block;
}

.hiss-hide {
  display: none;
}
.config p {
  margin-top: 20px;
  padding-bottom: 5px;
}
</style>
